package com.quzi.kettle.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import android.util.Log;

public class HttpUtil {

	public static final int SERVER_TIMEOUT_DEFAULT = 3000;
	int serverTimeout = SERVER_TIMEOUT_DEFAULT;

	private static HttpUtil httpUtil;

	private final boolean POST = true;
	private final boolean GET = false;

	public static HttpUtil getInstance() {
		if (httpUtil == null) {
			httpUtil = new HttpUtil();
		}
		return httpUtil;
	}

	public void setServerTimeout(int serverTimeout) {
		this.serverTimeout = serverTimeout;
	}

	private HttpUtil() {

	}

	enum RequestType {
		GET, POST
	}

	public String get(String urlStr) {
		return request(RequestType.GET, urlStr, null, GET);
	}

	public String post(String urlStr, String data) {
		Log.i("postData", "" + urlStr + "  " + data);
		return request(RequestType.POST, urlStr, data, POST);
	}

	private String request(RequestType type, String urlStr, String data,
			boolean isPost) {

		HttpURLConnection connection = null;

		try {
			connection = getConnection(type, urlStr, isPost);
			if (type == RequestType.POST) {
				writeData(connection, data);
			}

			int responseCode = connection.getResponseCode();
			if (responseCode == 200) {
				return changeInputStream(connection.getInputStream(), "utf-8");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "{\"errorCode\":\"-1\",\"msg\":\"请求超时,请检查网络\"}";
		} finally {

			if (connection != null) {
				connection.disconnect();
			}
		}
		return "reponseCode may not 200 or server problem";

	}

	// 获取HttpURLConnection
	private HttpURLConnection getConnection(RequestType type, String urlStr,
			boolean isPost) throws Exception {
		URL url = new URL(urlStr);

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		connection.setDoInput(true);
		if (type == RequestType.POST) {
			connection.setDoOutput(true);
		}
		connection.setRequestMethod(type.name());

		connection.setRequestProperty("Accept-Charset", "utf-8");
		if (isPost) {

			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

		}
		connection.setRequestProperty("Authorization", "Basic YWRtaW46cGFzc3dvcmQ=");
		connection.setConnectTimeout(serverTimeout);
		connection.setReadTimeout(serverTimeout);
		// connection.connect();
		return connection;
	}

	// 向服务器发送数据
	private void writeData(HttpURLConnection connection, String data)
			throws IOException {
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		out.write(data.getBytes(), 0, new StringBuffer(data).length());
		out.flush();
		out.close();
	}

	// 请求体封装
	public StringBuffer getRequestData(Map<String, String> params, String encode) {
		StringBuffer sBuffer = new StringBuffer();
		// sBuffer.append("?");
		try {
			if (params != null && !params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					sBuffer.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), encode))
							.append("&");
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		sBuffer.deleteCharAt(sBuffer.length() - 1);

		return sBuffer;
	}

	// 请求数据返回
	private static String changeInputStream(InputStream inputStream,
			String encode) {

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		try {
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
			result = new String(outputStream.toByteArray(), encode);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}
}
